package com.pcbly.web.bean.user;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pcbly.web.bean.AbstractBaseBean;
import com.pcbly.web.components.utils.security.Base64;
import com.pcbly.web.components.utils.security.DES;
import com.pcbly.web.config.SysConfig;

public class UserCookie extends AbstractBaseBean {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4587321272307846320L;
	private static final Log logger = LogFactory.getLog(UserCookie.class);

	private static final String PASS_USERNAME_KEY = "PASS_USERNAME";

	private static final String PASS_USERNAME_DES_KEY = "PASS_USERNAME_DES";

	private static final String LIGHTSOFT_TIMEZONE_KEY = "TZ";

	private static final String LIGHTSOFT_AUTHCODE = "AC";

	private static final String LIGHTSOFT_USERNAME = "U";

	private static final String LIGHTSOFT_PASSWD = "P";

	private HttpServletRequest request;

	private HttpServletResponse response;

	private SysConfig sysConfig;

	private DES des;

	private String timeZone = "GMT+08:00";

	private String pusername = "";

	private String pusernamedes = "";

	private long lastSendNoteTime = 0;

	private long lastPostTime = 0;

	private int editType = 0;

	private String authCode = "";

	private String userName = "";

	private String passwd = "";

	public UserCookie(HttpServletRequest request, HttpServletResponse response,
			SysConfig sysConfig) {
		this.request = request;
		this.response = response;
		this.sysConfig = sysConfig;
		try {
			des = new DES(DES._DESede);
		} catch (Exception ex) {
			logger.error(ex);
		}
		getCookies();
	}

	private void getCookies() {
		Cookie cookies[] = request.getCookies();
		Cookie sCookie = null;
		byte[] buf;
		try {
			if (cookies != null && cookies.length > 0) {
				for (int i = 0; i < cookies.length; i++) {
					sCookie = cookies[i];
					if (this.sysConfig.isUsePass()) {
						if (sCookie.getName().equals(PASS_USERNAME_KEY)) {
							this.pusername = sCookie.getValue();
							// System.out.println("pass username:" + username);
						}
						if (sCookie.getName().equals(PASS_USERNAME_DES_KEY)) {
							if (StringUtils.isNotBlank(sCookie.getValue())) {
								buf = Base64.decode(java.net.URLDecoder.decode(
										sCookie.getValue(), "UTF-8"));
								byte[] dec = des.decode(buf, Base64
										.decode(this.sysConfig.getCookieKey()));
								this.pusernamedes = new String(dec);
							}
						}
					}

					if (sCookie.getName().equals(LIGHTSOFT_AUTHCODE)) {
						if (StringUtils.isNotBlank(sCookie.getValue())) {
							buf = Base64.decode(java.net.URLDecoder.decode(
									sCookie.getValue(), "UTF-8"));
							byte[] dec = des.decode(buf, Base64
									.decode(this.sysConfig.getCookieKey()));
							this.authCode = new String(dec);
						}
					}
					if (sCookie.getName().equals(LIGHTSOFT_USERNAME)) {
						if (StringUtils.isNotBlank(sCookie.getValue())) {
							this.userName = sCookie.getValue();
						}
					}
					if (sCookie.getName().equals(LIGHTSOFT_PASSWD)) {
						if (StringUtils.isNotBlank(sCookie.getValue())) {
							buf = Base64.decode(java.net.URLDecoder.decode(
									sCookie.getValue(), "UTF-8"));
							byte[] dec = des.decode(buf, Base64
									.decode(this.sysConfig.getCookieKey()));
							this.passwd = new String(dec);
						}
					}
				}
			}
		} catch (Exception ex) {
			logger.error(ex);
		}
	}

	public void addC(String name, String value) {
		Cookie cookies = new Cookie(name, value);
		cookies.setPath(this.sysConfig.getCookiePath());
		cookies.setMaxAge(-1);
		// cookies.setMaxAge(30 * 60);
		if (StringUtils.isNotBlank(this.sysConfig.getCookieDomain())) {
			cookies.setDomain(this.sysConfig.getCookieDomain());
		}
		this.response.addCookie(cookies);
	}

	public void addDES(String name, String value) {
		try {
			des.setKey(Base64.decode(this.sysConfig.getCookieKey()));
			byte[] enc = des.encode(value.getBytes());
			value = java.net.URLEncoder.encode(Base64.encode(enc), "UTF-8");
			Cookie cookies = new Cookie(name, value);
			cookies.setPath(this.sysConfig.getCookiePath());
			// cookies.setMaxAge(30 * 60);
			cookies.setMaxAge(-1);
			if (StringUtils.isNotBlank(this.sysConfig.getCookieDomain())) {
				cookies.setDomain(this.sysConfig.getCookieDomain());
			}
			this.response.addCookie(cookies);
		} catch (Exception ex) {
			// ex.printStackTrace();
			logger.error("addDES(String name, String value)" + ex);
		}
	}

	public void addC(String name, String value, int maxage) {
		Cookie cookies = new Cookie(name, value);
		cookies.setPath(this.sysConfig.getCookiePath());
		cookies.setMaxAge(maxage);
		// cookies.setMaxAge(30 * 60);
		if (StringUtils.isNotBlank(this.sysConfig.getCookieDomain())) {
			cookies.setDomain(this.sysConfig.getCookieDomain());
		}
		this.response.addCookie(cookies);
	}

	public void addDES(String name, String value, int maxage) {
		try {
			// DES des = new DES(DES._DESede);
			des.setKey(Base64.decode(this.sysConfig.getCookieKey()));
			byte[] enc = des.encode(value.getBytes());
			// value = Util.base64Encode(enc);
			value = java.net.URLEncoder.encode(Base64.encode(enc), "UTF-8");
			Cookie cookies = new Cookie(name, value);
			cookies.setPath(this.sysConfig.getCookiePath());
			// cookies.setMaxAge(30 * 60);
			cookies.setMaxAge(maxage);
			if (StringUtils.isNotBlank(this.sysConfig.getCookieDomain())) {
				cookies.setDomain(this.sysConfig.getCookieDomain());
			}
			this.response.addCookie(cookies);
		} catch (Exception ex) {
			// ex.printStackTrace();
			logger.error("addDES(String name, String value)" + ex);
		}
	}

	public void addCookies(UserBean ui) {

	}

	public void addGuestCookies() {
		this.timeZone = "GMT+08:00";
		addC(LIGHTSOFT_TIMEZONE_KEY, Base64.encode(this.timeZone.getBytes()),
				-1);
		this.editType = -1;
	}

	public void addAuthCode(String authCode) {
		this.addDES(LIGHTSOFT_AUTHCODE, authCode, -1);
	}

	public void removeAuthCode() {
		this.addC(LIGHTSOFT_AUTHCODE, "", 0);
	}

	public void removeAllCookies() {
		addC(LIGHTSOFT_AUTHCODE, "", 0);
		addC(LIGHTSOFT_USERNAME, "", 0);
		addC(LIGHTSOFT_PASSWD, "", 0);
	}

	public void removePassCookies() {
		addC(PASS_USERNAME_KEY, "", 0);
		addC(PASS_USERNAME_DES_KEY, "", 0);
	}

	public boolean isLoginPass() {
		if (StringUtils.isNotBlank(this.pusername)
				&& StringUtils.isNotBlank(this.pusernamedes)
				&& this.pusername.equals(this.pusernamedes)) {
			return true;
		}
		return false;
	}

	public boolean isSaveLoginCookie() {
		if (StringUtils.isNotBlank(this.userName)
				&& StringUtils.isNotBlank(this.passwd)) {
			return true;
		} else {
			return false;
		}
	}

	public String getTimeZone() {
		return timeZone;
	}

	public String getPusername() {
		return pusername;
	}

	public String getPusernamedes() {
		return pusernamedes;
	}

	public long getLastPostTime() {
		return lastPostTime;
	}

	public long getLastSendNoteTime() {
		return lastSendNoteTime;
	}

	public int getEditType() {
		return editType;
	}

	public void setTimeZone(String timeZone) {
		this.timeZone = timeZone;
	}

	public void setPusername(String pusername) {
		this.pusername = pusername;
	}

	public void setPusernamedes(String pusernamedes) {
		this.pusernamedes = pusernamedes;
	}

	public void setLastPostTime(long lastPostTime) {
		this.lastPostTime = lastPostTime;
	}

	public void setLastSendNoteTime(long lastSendNoteTime) {
		this.lastSendNoteTime = lastSendNoteTime;
	}

	public void setEditType(int editType) {
		this.editType = editType;
	}

	public String getAuthCode() {
		return authCode;
	}

	public void setAuthCode(String authCode) {
		this.authCode = authCode;
	}

	public String getPasswd() {
		return passwd;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	/**
	 * @see java.lang.Object#equals(Object)
	 */
	public boolean equals(Object object) {
		return EqualsBuilder.reflectionEquals(this, object);
	}

	/**
	 * @see java.lang.Object#hashCode()
	 */
	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this);
	}

	/**
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		return ToStringBuilder.reflectionToString(this,
				ToStringStyle.MULTI_LINE_STYLE);
	}

}
